# app/models/friend.py
from app import db
from datetime import datetime
from sqlalchemy import Enum, CheckConstraint

class FriendGroup(db.Model):
    __tablename__ = 'friend_groups'

    group_id = db.Column(db.String(36), primary_key=True)
    user_id = db.Column(db.String(36), db.ForeignKey('users.user_id'), nullable=False)
    group_name = db.Column(db.String(50), nullable=False)
    position = db.Column(db.Integer, default=0)

    user = db.relationship('User', back_populates='friend_groups')
    friends = db.relationship('Friend', back_populates='group')

    def __repr__(self):
        return f'<FriendGroup {self.group_name} for {self.user.username}>'


class Friend(db.Model):
    __tablename__ = 'friends'
    __table_args__ = (
        # 防止重复好友关系
        db.UniqueConstraint('user_id', 'friend_id', name='unique_friendship'),
        # 防止自关联
        CheckConstraint('user_id != friend_id', name='no_self_friend')
    )

    friendship_id = db.Column(db.String(36), primary_key=True)
    user_id = db.Column(db.String(36), db.ForeignKey('users.user_id'), nullable=False)
    friend_id = db.Column(db.String(36), db.ForeignKey('users.user_id'), nullable=False)
    status = db.Column(Enum('pending', 'accepted', 'blocked', name='friend_status'), nullable=False)
    group_id = db.Column(db.String(36), db.ForeignKey('friend_groups.group_id'))
    created_at = db.Column(db.DateTime, default=datetime.utcnow)

    initiator = db.relationship('User', foreign_keys=[user_id], back_populates='initiated_friendships')
    friend = db.relationship('User', foreign_keys=[friend_id], back_populates='received_friendships')
    group = db.relationship('FriendGroup', back_populates='friends')

    def __repr__(self):
        return f'<Friend {self.initiator.username} - {self.friend.username} ({self.status})>'